package com.xy6.model.service;

import java.util.concurrent.Future;

import com.xy6.model.api.service.IMyExecutorService;
import com.xy6.model.api.vo.MyJob;
import com.xy6.model.service.monitor.MyFutureMonitor;
import com.xy6.model.service.monitor.MyJobMonitor;
import com.xy6.model.service.monitor.MyThreadMonitor;
import com.xy6.model.thread.MyJobThread;
import com.xy6.model.utils.MySystem;

public class MyExecutorService implements IMyExecutorService {

	@Override
	public String submit(String jobId) {
		MySystem.println(String.format("client submit a job %s", jobId));
		if(MyJobMonitor.containsId(jobId)){
			return "job already exists";
		}
		MyJobMonitor.putId(jobId);
		MyJobThread jobThread = new MyJobThread(make(jobId));
		@SuppressWarnings("rawtypes")
		Future future = MyThreadPool.submit(jobThread);
		// 保存线程对象，用于挂起、恢复等操作
		MyThreadMonitor.put(jobId, jobThread);
		// 保存线程，用于强制停止
		MyFutureMonitor.put(jobId, future);
		return "";
	}

	@Override
	public String suspend(String jobId) {
		MySystem.println(String.format("client suspend a job %s", jobId));
		if (!MyJobMonitor.contains(jobId)) {
			return "job does not exists";
		}
		MyJobThread t = MyThreadMonitor.get(jobId);
		t.mysuspend();
		return "";
	}

	@Override
	public String resume(String jobId) {
		MySystem.println(String.format("client resume a job %s", jobId));
		if (!MyJobMonitor.contains(jobId)) {
			return "job does not exists";
		}
		MyJobThread t = MyThreadMonitor.get(jobId);
		t.myresume();
		return "";
	}

	@Override
	public String stop(String jobId) {
		MySystem.println(String.format("client stop a job %s", jobId));
		if (!MyJobMonitor.contains(jobId)) {
			return "job does not exists";
		}
		MyJobThread t = MyThreadMonitor.get(jobId);
		t.mystop();
		return "";
	}

	@Override
	public String forceStop(String jobId) {
		MySystem.println(String.format("client forceStop a job %s", jobId));
		if (!MyFutureMonitor.contains(jobId)) {
			return "job does not exists";
		}
		@SuppressWarnings("rawtypes")
		Future future = MyFutureMonitor.get(jobId);
		future.cancel(true);
		return "";
	}

	private static MyJob make(String jobId) {
		MyJob job = new MyJob();
		job.setId("j001");
		job.setCron("* * * * * ?");
		job.setTaskIds("t001,t002,t003,t004");
		job.setLines("t001,t002;t001,t003;t002,t004;t003,t004");
		
		return job;
	}

}
